package smartcrud.spring.controllers.rbac;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import smartcrud.common.orm.Page;
import smartcrud.common.orm.PropertyFilter;
import smartcrud.common.orm.jdbc.JdbcUtils;
import smartcrud.spring.models.rbac.Menu;
import smartcrud.spring.models.rbac.MenuService;

/**
 * Rails 1.2中对REST的实现默认把controller中的方法限制在7个：<br>
 * index、show、new、edit、create、 update和destroy.<br>
 * 而根据SpringSide4,使用Restful风格的Urls:<br>
 * 
 * <pre>
 * List page     : GET  /menu/ 
 * Show page     : GET  /menu/{id}
 * Create page   : GET  /menu/create
 * Create action : POST /menu/create
 * Update page   : GET  /menu/update/{id}
 * Update action : POST /menu/update
 * Delete action : GET  /menu/delete
 * </pre>
 * 
 * @author cyper.yin
 * 
 */
@Controller
@RequestMapping(value = "/menu")
public class MenuController {
	private static final String SUCCESS = "redirect:/menu/";

	@Autowired
	private MenuService menuService;

	@RequestMapping(value = "")
	public String index(
			@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
			Model model, 
			HttpServletRequest request) {
		
		List<PropertyFilter> filters = JdbcUtils.buildPropertyFilters(request);
		
		Page<Menu> page = new Page<Menu>(20);
		page.setPageIndex(pageIndex);
		page.orderBy("menu_order");
		page.order(Page.ASC);
		page = menuService.findByPage(page,filters);
		
		model.addAttribute("page", page);
		
		return "menu/menu_index";
	}

	@RequestMapping("/{id}")
	public ModelAndView show(@PathVariable("id") Long id) {
		Menu menu = menuService.findMenuById(id);
		ModelAndView mv = new ModelAndView("menu/menu_show");
		mv.addObject(menu);

		return mv;
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(ModelMap model) {
		model.addAttribute("topLevelMenus",menuService.findTopLevelMenus());
		
		int menuCount = menuService.count();
		model.addAttribute("menuCount",menuCount);
		
		Menu menu = new Menu();
		menu.setMenuOrder(menuCount);
		model.addAttribute(menu);
		return "menu/menu_new";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@ModelAttribute("menu") Menu menu,
			RedirectAttributes redirectAttributes) {
		menuService.createMenu(menu);
		redirectAttributes.addFlashAttribute("message", "create success!");

		return SUCCESS;
	}
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}
	
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(Model model, @PathVariable("id") Long id) {
		model.addAttribute("topLevelMenus",menuService.findTopLevelMenus());
		
		Menu menu = menuService.findMenuById(id);
		model.addAttribute(menu);
		return "menu/menu_edit";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@ModelAttribute("menu") Menu menu,
			RedirectAttributes redirectAttributes) {
		menuService.updateMenu(menu);
		redirectAttributes.addFlashAttribute("message", "update success!");
		return SUCCESS;
	}
	
	@RequestMapping(value = "moveRow", method = RequestMethod.POST)
	public @ResponseBody String moveRow(HttpServletRequest request) {
		Map<String,String[]> map = request.getParameterMap();
		List<Menu> menus = new ArrayList<Menu>();
		for(String key: map.keySet()){
			Menu menu = new Menu();
			menu.setId(Long.valueOf(key));
			menu.setMenuOrder(Integer.valueOf(request.getParameter(key)));
			menus.add(menu);
			System.out.println(menu.getId()+"," + menu.getMenuOrder());
		}
		menuService.updateMenuOrder(menus);
		return "ok";
	}
	
	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id,
			RedirectAttributes redirectAttributes) {
		menuService.deleteMenu(id);
		redirectAttributes.addFlashAttribute("message", "delete success!");
		return SUCCESS;
	}
}
